package com.merryituxz.o2o.service.impl;

import com.merryituxz.o2o.dto.ImageHolder;
import com.merryituxz.o2o.dto.ShopExecution;
import com.merryituxz.o2o.entity.Shop;
import com.merryituxz.o2o.entity.ShopAuthMap;
import com.merryituxz.o2o.enums.ShopStateEnum;
import com.merryituxz.o2o.exceptions.ShopOperationException;
import com.merryituxz.o2o.mapper.ShopAuthMapMapper;
import com.merryituxz.o2o.mapper.ShopMapper;
import com.merryituxz.o2o.service.ShopService;
import com.merryituxz.o2o.util.ImageUtil;
import com.merryituxz.o2o.util.PageCalculator;
import com.merryituxz.o2o.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopAuthMapMapper shopAuthMapMapper;

    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, ImageHolder thumbnail) {
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        try {
            shop.setEnableStatus(0); // 审核中
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            int effectedNum = shopMapper.insertShop(shop);
            if (effectedNum <= 0) {
                throw new ShopOperationException("店铺创建失败");
            } else {
                // 如果shopImgInputStream不为空则存储图片,并更新店铺
                if (thumbnail.getImage() != null) {
                    try {
                        addShopImg(shop, thumbnail);
                    } catch (Exception e) {
                        throw new ShopOperationException("addShopImg error: " + e.getMessage());
                    }
                    effectedNum = shopMapper.updateShop(shop);
                    if (effectedNum <= 0) {
                        throw new ShopOperationException("更新图片地址失败");
                    }
                    // 增加shopAuthMap
                    ShopAuthMap shopAuthMap = new ShopAuthMap();
                    shopAuthMap.setEmployee(shop.getOwner());
                    shopAuthMap.setShop(shop);
                    shopAuthMap.setTitle("店家");
                    shopAuthMap.setTitleFlag(0);
                    shopAuthMap.setCreateTime(new Date());
                    shopAuthMap.setLastEditTime(new Date());
                    shopAuthMap.setEnableStatus(1);
                    try {
                        effectedNum = shopAuthMapMapper.insertShopAuthMap(shopAuthMap);
                        if (effectedNum <= 0) {
                            throw new ShopOperationException("授权创建失败");
                        }
                    } catch (Exception e) {
                        throw new ShopOperationException("insertShopAuthMap error: " + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            throw new ShopOperationException("addShop error: " + e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }

    @Override
    public Shop getByShopId(long shopId) {
        return shopMapper.queryByShopId(shopId);
    }

    @Override
    public ShopExecution modifyShop(Shop shop, ImageHolder thumbnail) {
        if (shop == null || shop.getShopId() == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        } else {
            try {
                // 判断是否要处理图片
                if (thumbnail.getImage() != null && thumbnail.getImageName() != null && !thumbnail.getImageName().equals("")) {
                    Shop tempShop = shopMapper.queryByShopId(shop.getShopId());
                    if (tempShop.getShopImg() != null) {
                        ImageUtil.deleteFileOrPath(tempShop.getShopImg());
                    }
                    addShopImg(shop, thumbnail);
                }
                // 更新店铺信息
                shop.setLastEditTime(new Date());
                int effectedNum = shopMapper.updateShop(shop);
                if (effectedNum <= 0) {
                    return new ShopExecution(ShopStateEnum.INNER_ERROR);
                } else {
                    shop = shopMapper.queryByShopId(shop.getShopId());
                    return new ShopExecution(ShopStateEnum.SUCCESS, shop);
                }
            } catch (Exception e) {
                throw new ShopOperationException("modifyShop error: " + e.getMessage());
            }
        }
    }

    @Override
    public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
        int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
        List<Shop> shopList = shopMapper.queryShopList(shopCondition, rowIndex, pageSize);
        int count = shopMapper.queryShopCount(shopCondition);
        ShopExecution shopExecution = new ShopExecution();
        if (shopList != null) {
            shopExecution.setShopList(shopList);
            shopExecution.setCount(count);
        } else {
            shopExecution.setState(ShopStateEnum.INNER_ERROR.getState());
        }
        return shopExecution;
    }

    /**
     * 生成图片并更新shop的图片地址shopImgInputStreamAddr
     *
     * @param shop      店铺
     * @param thumbnail 图片(封装了图片流+图片名称)
     */
    private void addShopImg(Shop shop, ImageHolder thumbnail) {
        String dest = PathUtil.getShopImgPath(shop.getShopId());
        String shopImgInputStreamAddr = ImageUtil.generateThumbnail(thumbnail, dest);
        shop.setShopImg(shopImgInputStreamAddr);
    }
}
